package com.caigou.modules.personal.ui.info

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bean.Session
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.GlideEngine
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.utils.SessionUtil
import com.caigou.modules.personal.R
import com.caigou.modules.personal.databinding.FragmentInfoMainBinding
import com.caigou.modules.personal.viewmodel.PersonalInfoViewModel
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import dagger.hilt.android.AndroidEntryPoint
import java.io.File

/**
 * @author #Suyghur.
 * Created on 2021/10/09
 */
@AndroidEntryPoint
class InfoMainFragment : BaseFragment(), View.OnClickListener {

    private var _binding: FragmentInfoMainBinding? = null
    private val binding get() = _binding!!

    private val personalInfoViewModel: PersonalInfoViewModel by viewModels()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentInfoMainBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        if (TextUtils.isEmpty(AppBackgroundInfo.instance.userBean!!.headImg)) {
            binding.avatarIvDisplay.setImageResource(R.drawable.img_comm_avatar)
        } else {
            ImageLoader.loadCircle(requireActivity(), AppBackgroundInfo.instance.userBean!!.headImg, binding.avatarIvDisplay)
        }
        binding.nicknameIvDisplay.text = AppBackgroundInfo.instance.userBean!!.nickName
        binding.realnameIvDisplay.text = AppBackgroundInfo.instance.userBean!!.realName
        binding.mobileIvDisplay.text = AppBackgroundInfo.instance.userBean!!.mobile
        binding.signatureIvDisplay.text = if (TextUtils.isEmpty(AppBackgroundInfo.instance.userBean!!.signature)) {
            "请勿发布联系方式网址等，否则禁言处理..."
        } else {
            AppBackgroundInfo.instance.userBean!!.signature
        }
        binding.codeTvDisplay.text = "点击复制邀请码：${AppBackgroundInfo.instance.userBean!!.ownInvitationCode}"

        binding.infoTvModify.setOnClickListener(this)
        binding.infoClAvatar.setOnClickListener(this)
        binding.infoClNickname.setOnClickListener(this)
        binding.infoClRealname.setOnClickListener(this)
        binding.infoClSignature.setOnClickListener(this)
        binding.infoClLevel.setOnClickListener(this)
        binding.codeBtnCopy.setOnClickListener(this)
        binding.infoBtnLogout.setOnClickListener(this)

        binding.infoTvBack.setOnClickListener {
            requireActivity().finish()
        }
    }

    override fun lazyLoad() {

    }

    override fun onBack() {
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(personalInfoViewModel.uploadAvatarLiveData, ::handleUploadAvatar)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun openGallery() {
        PictureSelector.create(requireActivity())
            .openGallery(PictureMimeType.ofImage())
            .theme(R.style.picture_WeChat_style)
            .imageEngine(GlideEngine.instance)
            .imageSpanCount(4)
            .isReturnEmpty(true)
            .selectionMode(PictureConfig.SINGLE)
            .maxSelectNum(1)
            .isPreviewImage(true)
            .isCamera(true)
            .isZoomAnim(true)
            .setCameraImageFormat(PictureMimeType.PNG)
            .isEnableCrop(true)
            .isCompress(true)
            .compressQuality(80)
            .synOrAsy(false)
            .withAspectRatio(1, 1)
            .freeStyleCropEnabled(false)
            .circleDimmedLayer(true)
            .cutOutQuality(90)
            .minimumCompressSize(100)
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: MutableList<LocalMedia>?) {
                    result?.apply {
                        val avatar = File(this[0].cutPath)
                        personalInfoViewModel.uploadAvatar(AppBackgroundInfo.instance.userBean!!.userId, avatar)
                    }
                }

                override fun onCancel() {
                }

            })
    }


    private fun handleUploadAvatar(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("修改个人头像异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
            }
        }
    }


    override fun onClick(v: View?) {
        v?.apply {
            when (id) {
                binding.infoTvModify.id -> {
                    (requireActivity() as PersonalInfoActivity).switchFragment(RouterPath.Personal.TAG_MODIFY)
                }
                binding.infoClAvatar.id -> {
                    openGallery()
                }
                binding.infoClNickname.id -> {
                    (requireActivity() as PersonalInfoActivity).switchFragment(RouterPath.Personal.TAG_NICK_NAME)
                }
                binding.infoClRealname.id -> {
                    (requireActivity() as PersonalInfoActivity).switchFragment(RouterPath.Personal.TAG_REAL_NAME)
                }
                binding.infoClSignature.id -> {
                    (requireActivity() as PersonalInfoActivity).switchFragment(RouterPath.Personal.TAG_SIGNATURE)
                }
                binding.infoClLevel.id -> {
                    (requireActivity() as PersonalInfoActivity).switchFragment(RouterPath.Personal.TAG_LEVEL)
                }
                binding.codeBtnCopy.id -> {
                    val cm = requireActivity().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    val mClipData = ClipData.newPlainText("ownInvitationCode", AppBackgroundInfo.instance.userBean!!.ownInvitationCode)
                    cm.setPrimaryClip(mClipData)
                    showToast("复制成功")
                }
                binding.infoBtnLogout.id -> {
                    SessionUtil.setSession(Session("", ""))
                    AppBackgroundInfo.instance.reset()
                    LiveDataBus.get().with(BusKey.LOGOUT_SUCCESS).value = Any()
                    requireActivity().finish()
                }
            }
        }
    }
}